package com.liyiruo.uploadfiles.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author liyiruo
 * @Description
 * @Date 2024/7/8 下午4:11
 */

@Controller
@RequestMapping("upload")
@Slf4j
public class DirController {
    private static final String UPLOAD_DIR = "files";
    @RequestMapping("/dir")
    @ResponseBody
    public String uploadFiles(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
        String uploadRootPath = request.getServletContext().getRealPath("/") + UPLOAD_DIR;
        uploadRootPath=UPLOAD_DIR;
        File uploadRootDir = new File(uploadRootPath);

        // 如果不存在，创建目录
        if (!uploadRootDir.exists()) {
            uploadRootDir.mkdirs();
        }

        for (MultipartFile file : files) {
            try {
                String originalFileName = file.getOriginalFilename();
                String filePath = uploadRootPath + File.separator + originalFileName;
                Path destinationPath = Paths.get(filePath);

                //如果文件不存在，应该先创建
                Path parentDir = Paths.get(filePath).getParent();
                // 检查父目录是否存在，如果不存在，则创建它
                if (parentDir != null && !Files.exists(parentDir)) {
                    try {
                        // 创建目录，包括所有必需的父目录
                        Files.createDirectories(parentDir);
                        System.out.println("目录已创建: " + parentDir);
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.out.println("创建目录失败");
                    }
                }


                Files.write(destinationPath, file.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
                return "上传文件失败：" + e.getMessage();
            }
        }

        return "文件上传成功！";
    }
}
